<template>
	<!-- 资产列表 -->
	<view class="assetMain">
		<picker :range="pickerRange" @change="bindPickerChange" :mode="pickerMode" fields="month" @cancel="cancelPicker">
			<view class="tab-posi">
				<NewSegmentedControl :current="current" :values="items" style-type="text" active-color="#198a6c"
					@clickItem="onClickItem" />
			</view>
		</picker>

		<searchPopup :show="toShow" ref="toSearch" @clickFu="receive" />

		<view class="assetList">
			<view class="assetListItem" v-for="(item,index) in assetsList" :key="index">
				<view class="itemHead">
					<view class="itemHeadTitle">
						{{item.assetName}}
					</view>
					<view class="itemHeadState"
						:class="item.statusCh=='使用中'?'color-b-bg':item.statusCh=='闲置中'?'color-p-bg':item.statusCh=='已报废'||item.statusCh=='故障中'?'color-r-bg':'color-y-bg'">
						{{item.statusCh?item.statusCh:'未知'}}
					</view>
				</view>
				<view class="itemContent" @click="toDetail(item)">
					<view class="conCenter">
						<view>资产类型：<view class="v-m color-green">{{item.assetTypeCh}}</view>
						</view>
						<view>资产编号：{{item.assetNo}}</view>
						<view>存放位置：{{item.storageLocationName}}</view>
						<!-- <view>出厂日期：{{item.manufactureDate}}</view> -->
						<view>
							资产管理类型：{{item.manageTypeName}}
						</view>
						<view>购入日期：{{item.purchaseDate}}</view>
						<view>维保期限：{{item.warrantyExpires}}</view>
						<view style="color: #999;">备注信息：{{item.remarks}}</view>
					</view>
					<view>
						<text class="iconfont">&#xe8d4;</text>
					</view>
				</view>
				<view :class="{'itemHand':true,'permission-none':isPermission('ASS_APP_INSERT')}" v-if="item.statusCh=='使用中'">
					<!-- <view @click="toRetrue(item)" class="btn-s btn-orange-s"> 退回</view> -->
					<view @click="toUnUsed(item)" class="btn-s btn-orange-s"> 闲置</view>
					<view @click="toRepair(item)" class="btn-s btn-green-s">报修</view>
					<view @click="toScrap(item)" class="btn-s btn-red-s">报废</view>
				</view>
			</view>
			<!-- 加载结束 -->
			<view class="uni-loadmore" v-if="showLoadMore">{{loadMoreText}}</view>
		</view>


		<view class="bottom-btn">
			<button class="start-button" @click="scan"><text
					class="iconfont icon-saoyisao"></text>&nbsp;&nbsp;识别资产</button>
		</view>
		
		<MessageTip ref="messageTip" tipContent="确定闲置该资产吗？" @clickType="handleShowOrHideTip"/>

	</view>
</template>

<script lang="ts">
	import {
		onPullDownRefresh,
		onReachBottom,
		onNavigationBarButtonTap,
		onLoad
	} from "@dcloudio/uni-app";

	import searchPopup from '@/pages/searchPopup/index.vue'

	import {
		defineComponent,
		ref,
		reactive
	} from 'vue'
	import {
		assetList,
		assetType,
		unusedAsset
	} from '@/common/api/assetAPI.ts'
	import {
		assetStatus,
		getPosition
	} from '@/common/api/comAPI.ts'
	import {
		CONSTANT
	} from '@/common/config/config.ts'
	import {
		fromSearch
	} from '@/common/util/tabSearchUse.ts'
	import {isPermission} from '@/common/util/common.ts'

	export default defineComponent({
		components: {
			searchPopup,
		},
		setup(props, {
			emit
		}) {
			const messageTip = ref()
			//获取列表数据
			const searchParams = ref({
				storageLocationName: null,
				status: null,
				assetType: null,
				purchaseDate: null,
				assetId: null,
				storageLocation: null,
				assetName:''
			}); //查询条件
			const matchRule = {
				storageLocationName: 'eq',
				status: 'eq',
				assetType: 'eq',
				purchaseDate: 'cn',
				assetId: 'eq',
				storageLocation: 'eq',
				assetName:'cn'
			}; //匹配条件
			const current = ref(0);
			const items = ref(["存放位置", "购入日期", "资产类型", "资产状态"]);
			const pickerRange = ref();
			const currentTab = ref(0);
			const pickerMode = ref('selector');

			const showLoadMore = ref(false);
			const loadMoreText = ref('加载中……'); //加载更多提示
			const assetsList = ref([]); //资产列表数据

			const assetStatusOpts = ref([]);

			const toSearch = ref(null);
			const assetTypeOpt = ref([]);
			assetType().then(res => {
				if (res.code === 0) {
					assetTypeOpt.value = res.data.map((item: any) => {
						return {
							label: item.enumName,
							value: item.sysEnumId
						}
					});
				}
			});
			// 搜索了列表
			function receive(e: any) {
				searchParams.value.assetName = e
				assetsList.value = []
				getList();
			}
			const toShow = ref(1)
			// 点击了搜索
			onNavigationBarButtonTap(() => {
				// 弹出搜索
				toShow.value++
			})

			const page = ref(CONSTANT.initPage); //初始加载页码
			const allPages = ref(0); //总页码数
			onPullDownRefresh(() => {
				page.value = CONSTANT.initPage; //重置页码
				assetsList.value = []; //重置列表
				getList();
			});
			onReachBottom(() => {
				//触发底部
				if (page.value > allPages.value || page.value == allPages.value) {
					loadMoreText.value = '没有更多的数据了'
					showLoadMore.value = true;
				} else {
					page.value++;
					loadMoreText.value = '加载中……';
					showLoadMore.value = true;
					getList();
				}

			})
			
			onLoad(param => {
				searchParams.value.assetId = param.assetId
				getList();
			})
			getEmuns();

			function getList() {
				let config = {
					page: page.value,
					rows: CONSTANT.pageSize
				}
				const params = Object.assign(fromSearch(searchParams.value, matchRule), config)
				loadMoreText.value = '加载中...'
				assetList(params).then((res: any) => {
					uni.stopPullDownRefresh(); //关闭下拉
					if (res.code === 0) {
						allPages.value = res.data.pages;
						page.value = res.data.current;
						let list: any[] = res.data.records;
						assetsList.value = assetsList.value.concat(list);
						if (assetsList.value.length === 0) {
							showLoadMore.value = true;
							loadMoreText.value = '暂无数据'
						} else if (assetsList.value.length < CONSTANT.pageSize) {
							showLoadMore.value = true;
							loadMoreText.value = '没有更多的数据了'
						} else {
							showLoadMore.value = false;
						}
					}

				})
			}
			//获取资产状态
			function getEmuns() {
				assetStatusOpts.value = [];
				assetStatus('AssetStatus').then((res: any) => {
					if (res.code === 0) {
						assetStatusOpts.value = res.data.AssetStatus.map((item: any) => {
							return {
								label: item.value,
								value: item.code
							}
						});
					}
				})
			}

			//----------------------------------------
			const positionList = ref([]); // 位置数据
			// 获取位置
			function getPos() {
				getPosition().then(value => {
					if (value.code == 0) {
						positionList.value = value.data.records.map((item: any) => {
							return {
								label: item.storeName,
								value: item.id
							}
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: '位置获取失败'
						});
					}
				})
			}
			getPos()

			//识别资产
			function scan() {
				uni.redirectTo({
					url: `/pages/qrCode/qrCode?tip=扫码失败？去资产列表&successUrl=/pages/assets/assetDetail/index&clickTipUrl=/pages/assets/assetManage/index&goBack=1`,
				})
			}

			// hanlder
			// 报修
			const toRepair = (item) => {
				const assetData = JSON.stringify(item)
				uni.navigateTo({
					url: `/pages/repairEquipment/submitRepairApply/index?assetData=${assetData}`,
				})
			}
			//  报废
			const toScrap = (item) => {
				const assetData = JSON.stringify(item)
				uni.navigateTo({
					url: `/pages/scrapEquipment/submitScrapApply/index?assetData=${assetData}`,
				})
			}
			// 退回
			const toRetrue = (item) => {
				const assetData = JSON.stringify(item)
				uni.navigateTo({
					url: `/pages/assets/assetDetail/toRetrue?assetData=${assetData}`,
				})
			}
			// 闲置
			const unusedObj = ref()
			const toUnUsed = (item)=>{
				unusedObj.value = item
				messageTip.value.openTip() //打开弹窗
			}
			const dialogConfirm = ()=>{
				unusedAsset([unusedObj.value]).then((res)=>{
					if(res.code==0){
						uni.showToast({
							title:res.message,
							icon:"none",
							duration:500
						})
						setTimeout(()=>{
							page.value = CONSTANT.initPage; //重置页码
							assetsList.value = []; //重置列表
							getList()
						},500)
					}else{
						uni.showToast({
							title:res.message,
							icon:"none"
						})
					}
				})
			}
			
			const handleShowOrHideTip = (type:string)=>{
					if(type=='yes'){
						dialogConfirm() //弹窗点击确定时执行的代码
					}
				}
			// 资产详情
			const toDetail = (item) => {
				// console.log(JSON.stringify(item));
				uni.navigateTo({
					url: `/pages/assets/assetDetail/index?qrCode=${JSON.stringify(item)}`
				})
			}


			//tab点击事件
			const onClickItem = (e: {
				currentIndex: number
			}) => {
				page.value = CONSTANT.initPage;
				currentTab.value = e.currentIndex;
				switch (e.currentIndex) {
					case 0:
						pickerMode.value = "selector";
						pickerRange.value = positionList.value.map((item: {
							label: string,
							value: string
						}) => item.label);
						pickerRange.value.push('全部')
						break
					case 1:
						pickerMode.value = "date";
						break
					case 2:
						pickerMode.value = "selector";
						pickerRange.value = assetTypeOpt.value.map((item: {
							label: string,
							value: string
						}) => item.label);
						pickerRange.value.push('全部')
						break
					case 3:
						pickerMode.value = "selector";
						pickerRange.value = assetStatusOpts.value.map((item: {
							label: string,
							value: string
						}) => item.label);
						pickerRange.value.push('全部')
						break
				}

			};
			const bindPickerChange = (e: any) => {
				let len = pickerRange.value?.length-1
				assetsList.value = [];
				if (currentTab.value == 0) {
					if(e.detail.value==len){
						items.value[0] = '存放位置'
						searchParams.value.storageLocation = null
					}else{
						items.value[0] = pickerRange.value[e.detail.value]
						searchParams.value.storageLocation = (positionList.value[e.detail.value] as EnumType).value
					}
					
				} else if (currentTab.value == 1) {
					items.value[1] = e.detail.value
					searchParams.value.purchaseDate = e.detail.value
				} else if (currentTab.value == 2) {
					if(e.detail.value==len){
						items.value[2] = '资产类型'
						searchParams.value.assetType = null
					}else{
						items.value[2] = pickerRange.value[e.detail.value]
						searchParams.value.assetType = (assetTypeOpt.value[e.detail.value] as EnumType).value
					}
				} else if (currentTab.value == 3) {
					if(e.detail.value==len){
						items.value[3] = '资产状态'
						searchParams.value.status = null
					}else{
						items.value[3] = pickerRange.value[e.detail.value]
						searchParams.value.status = (assetStatusOpts.value[e.detail.value] as EnumType).value
					}
					
				}
				getList()
			};
			const cancelPicker = ()=>{
				console.log(111);
				if(pickerMode.value=='date'){
					items.value[1]='购入日期'
					searchParams.value.purchaseDate = null
					getList()
				}
			}
			return {
				pickerRange,
				items,
				current,
				currentTab,
				pickerMode,
				showLoadMore,
				loadMoreText,
				assetsList,
				searchParams,
				scan,
				onClickItem,
				bindPickerChange,
				assetStatusOpts,
				toRepair,
				toScrap,
				toDetail,
				toRetrue,
				receive,
				toSearch,
				toShow,
				positionList,
				isPermission,
				cancelPicker,
				toUnUsed,
				handleShowOrHideTip,
				messageTip
			}
		},
	})
</script>

<style lang="scss">
	.conCenter>view:first-child {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.assetMain {
		background-color: #eee;
		font-size: 14px;
	}

	.assetNav {
		display: flex;
		flex-wrap: row nowrap;
		justify-content: space-around;
		padding: 15px;
		background-color: #fff;
	}

	.start-button {
		width: 60%;
		box-sizing: border-box;
		background-color: #198a6c;
		color: #fff;
		border-radius: 30px;
		line-height: 30px;
		font-size: 14px;
	}

	.assetList {
		padding: 30px 15px 80px 15px;
	}

	.itemHead {
		position: relative;
	}

	.assetListItem {
		margin-top: 15px;
		background-color: #fff;
		border-radius: 5px;
	}

	.itemHeadTitle {
		text-indent: 15px;
		box-sizing: border-box;
		padding-right: 80px;
		height: 40px;
		line-height: 40px;
		font-weight: bold;
		color: #333;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		border-bottom: 1px solid #ddd;
	}

	.itemHeadState {
		position: absolute;
		right: 0;
		top: 8px;
		display: inline-block;
		font-size: 11px;
		color: #fff;
		padding: 2px 12px;
		border-radius: 15px 0 0 15px;
	}

	.itemContent {
		box-sizing: border-box;
		font-size: 15px;
		padding: 15px 10px;
		border-bottom: 1px solid #eee;
		display: flex;
		flex-wrap: row nowrap;
	}

	.itemContent>view:nth-child(1) {
		width: 85%;
		padding-left: 15px;
		color: #333;
	}

	.itemContent>view:nth-child(1)>view {
		padding: 3px 0;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
		cursor: pointer;
	}

	.itemContent>view:nth-child(2) {
		width: 15%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.itemHand {
		padding: 8px 10px;
		display: flex;
		justify-content: flex-end;
	}

	.itemHand>view {
		padding: 4px 23px;
		font-size: 13px;
		border-radius: 4px;
		// border: 1px solid #369;
		// color: #369;
		margin-right: 14px;
	}

	.toQR {
		display: inline-block;
		width: 60%;
		background-color: #2AA37D;
		border-radius: 10px;
		color: #fff;

	}

	// picker适配问题
</style>
